<template>
  <div id="userLoginPage">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h2 class="title">无语筑</h2>
          <p class="desc">不写一行代码，生成完整应用</p>
        </div>

        <a-tabs v-model:activeKey="activeTab" centered>
          <a-tab-pane key="account" tab="账号登录">
            <a-form
              :model="accountForm"
              name="accountLogin"
              autocomplete="off"
              @finish="handleAccountLogin"
            >
              <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
                <a-input
                  v-model:value="accountForm.userAccount"
                  placeholder="请输入账号"
                  size="large"
                  allow-clear
                >
                  <template #prefix>
                    <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                name="userPassword"
                :rules="[
                  { required: true, message: '请输入密码' },
                  { min: 8, message: '密码长度不能小于 8 位' },
                ]"
              >
                <a-input-password
                  v-model:value="accountForm.userPassword"
                  placeholder="请输入密码"
                  size="large"
                  allow-clear
                >
                  <template #prefix>
                    <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
                </a-input-password>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  size="large"
                  :loading="loading"
                  block
                >
                  登录
                </a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>

          <a-tab-pane key="email" tab="邮箱登录">
            <a-form
              :model="emailForm"
              name="emailLogin"
              autocomplete="off"
              @finish="handleEmailLogin"
            >
              <a-form-item
                name="email"
                :rules="[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]"
              >
                <a-input
                  v-model:value="emailForm.email"
                  placeholder="请输入邮箱"
                  size="large"
                  allow-clear
                >
                  <template #prefix>
                    <MailOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item name="captcha" :rules="[{ required: true, message: '请输入验证码' }]">
                <a-input
                  v-model:value="emailForm.captcha"
                  placeholder="请输入验证码"
                  size="large"
                  allow-clear
                >
                  <template #prefix>
                    <SafetyOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
                  <template #suffix>
                    <a-button
                      type="link"
                      :disabled="countdown > 0"
                      :loading="sendingCode"
                      @click="sendVerificationCode"
                    >
                      {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                    </a-button>
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  html-type="submit"
                  size="large"
                  :loading="loading"
                  block
                >
                  登录
                </a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>

        <div class="login-footer">
          <span>没有账号？</span>
          <RouterLink to="/user/register" class="register-link">立即注册</RouterLink>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { userLogin, intoByEmail } from '@/api/userController'
import { intoEmail } from '@/api/emailController'
import { useLoginUserStore } from '@/stores/loginUser'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  SafetyOutlined,
} from '@ant-design/icons-vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 当前激活的标签页
const activeTab = ref('account')

// 账号登录表单
const accountForm = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

// 邮箱登录表单
const emailForm = reactive<API.EmailDto>({
  email: '',
  captcha: '',
})

// 加载状态
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

// 倒计时定时器
let timer: number | null = null

/**
 * 账号登录
 */
const handleAccountLogin = async (values: API.UserLoginRequest) => {
  try {
    loading.value = true
    const res = await userLogin(values)
    if (res.data.code === 0 && res.data.data) {
      await loginUserStore.fetchLoginUser()
      message.success('登录成功')
      router.push({
        path: '/',
        replace: true,
      })
    } else {
      message.error('登录失败，' + res.data.message)
    }
  } catch (error) {
    message.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 邮箱登录
 */
const handleEmailLogin = async (values: API.EmailDto) => {
  try {
    loading.value = true
    const res = await intoByEmail(values)
    if (res.data.code === 0 && res.data.data) {
      await loginUserStore.fetchLoginUser()
      message.success('登录成功')
      router.push({
        path: '/',
        replace: true,
      })
    } else {
      message.error('登录失败，' + res.data.message)
    }
  } catch (error) {
    message.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 发送验证码
 */
const sendVerificationCode = async () => {
  if (!emailForm.email) {
    message.warning('请先输入邮箱地址')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(emailForm.email)) {
    message.warning('请输入有效的邮箱地址')
    return
  }

  try {
    sendingCode.value = true
    const res = await intoEmail({ email: emailForm.email })
    if (res.data.code === 0) {
      message.success('验证码已发送，请查收邮箱')
      // 开始倒计时
      startCountdown()
    } else {
      message.error('发送失败，' + res.data.message)
    }
  } catch (error) {
    message.error('发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

/**
 * 开始倒计时
 */
const startCountdown = () => {
  countdown.value = 60
  if (timer) {
    clearInterval(timer)
  }
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer!)
      timer = null
    }
  }, 1000)
}

// 组件卸载时清除定时器
import { onUnmounted } from 'vue'
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
#userLoginPage {
  min-height: calc(100vh - 64px);
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(
      180deg,
      #f8fafc 0%,
      #f1f5f9 8%,
      #e2e8f0 20%,
      #cbd5e1 100%
    ),
    radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.12) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.08) 0%, transparent 50%);
  padding: 24px;
}

.login-container {
  width: 100%;
  max-width: 450px;
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-card {
  background: white;
  border-radius: 16px;
  padding: 40px 32px;
  margin-bottom: 200px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.title {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 50%, #10b981 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0 0 12px 0;
}

.desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

:deep(.ant-tabs) {
  margin-bottom: 24px;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 24px;
}

:deep(.ant-tabs-tab) {
  font-size: 16px;
  font-weight: 500;
  padding: 8px 16px;
}

:deep(.ant-tabs-tab-active) {
  color: #3b82f6;
}

:deep(.ant-tabs-ink-bar) {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
  height: 3px;
}

:deep(.ant-form-item) {
  margin-bottom: 20px;
}

:deep(.ant-input),
:deep(.ant-input-password) {
  border-radius: 8px;
  font-size: 14px;
}

:deep(.ant-input:hover),
:deep(.ant-input-password:hover .ant-input) {
  border-color: #3b82f6;
}

:deep(.ant-input:focus),
:deep(.ant-input-password:focus .ant-input),
:deep(.ant-input-focused),
:deep(.ant-input-password .ant-input-focused) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
  border: none;
  border-radius: 8px;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  transition: all 0.3s ease;
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(135deg, #2563eb 0%, #7c3aed 100%);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
  transform: translateY(-2px);
}

:deep(.ant-btn-primary:active) {
  transform: translateY(0);
}

:deep(.ant-btn-link) {
  color: #3b82f6;
  font-size: 13px;
  padding: 0;
}

:deep(.ant-btn-link:hover) {
  color: #2563eb;
}

:deep(.ant-btn-link:disabled) {
  color: #d9d9d9;
}

.login-footer {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
  color: #666;
  font-size: 14px;
}

.register-link {
  color: #3b82f6;
  font-weight: 500;
  margin-left: 8px;
  text-decoration: none;
  transition: color 0.3s ease;
}

.register-link:hover {
  color: #2563eb;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 576px) {
  .login-card {
    padding: 32px 24px;
  }

  .title {
    font-size: 24px;
  }

  .desc {
    font-size: 13px;
  }
}
</style>
